package com.gostudy.gulimall.product;

import com.gostudy.common.exception.BizCodeEnum;
import com.gostudy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: gulimall
 * @description: 统一异常处理类
 * @author: 53Hertz
 * @create: 2021-04-07 21:03
 **/
//作用就是用来统一处理异常的，有springMVC来提供的,并告诉它处理那些类里面的异常
//@ControllerAdvice(basePackages = "com.gostudy.gulimall.product.controller")
//@ResponseBody
//这一个等同于上面的两个注解
@RestControllerAdvice(basePackages = "com.gostudy.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {
    /*
    这个注解能够告诉springMVC这个方法能够处理那些异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            map.put(item.getField(),item.getDefaultMessage());
        });
        log.error("数据校验出错了！",e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(BizCodeEnum.UNKNOW_EXEPTION.getCode(),BizCodeEnum.UNKNOW_EXEPTION.getMsg());
    }
}
